var home = require("../../utils/util.js");
var url = home.home;
var url2 = home.home2;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: "",
    color: "color",
    bgcolor: home.getKey('bgcolor'),
    activeKey: 1,
    page: 1, //分页
    type: 1,
    cate: [],
    listData: [], //列表数据
    userId: home.getKey('userId'), //会员id
    cate_id1: '', //分类id
    cate_id2: '', //分类id
    state: wx.getStorageSync('state'),
    states: false,
    btnState:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      states:false,
      state: wx.getStorageSync('state'),
    });
  },

  /**
   * 跳转商品详情
   */
  toGoods(e) {
    let goodsId = e.currentTarget.dataset.id;
    let type = this.data.type;
    let info = {};
    for (let i = 0; i < this.data.listData.length; i++) {
      if (this.data.listData[i].id == goodsId) {
        info = this.data.listData[i];
      }        
    }
    if (type == 1) {
      wx.navigateTo({
        url: '../../shop/goods/index?info='+JSON.stringify(info),
      })
    } else {
      wx.navigateTo({
        url: '../../shop/project/index?info='+JSON.stringify(info),
      })
    }
  },

  /**
   * 切换sidebar
   */
  sidebar(e) {
    let type = this.data.cate[e.detail].parent;
    let cate_id1 = this.data.cate_id1;
    let cate_id2 = this.data.cate_id2;
    if (type == 1) {
      cate_id1 = this.data.cate[e.detail].id;
    } else {
      cate_id2 = this.data.cate[e.detail].id;
    }
    // let cate_id = this.data.cate[e.detail].id;
    this.setData({
      activeKey: e.detail,
      page: 1,
      type: type,
      cate_id1: cate_id1,
      cate_id2: cate_id2
    });
    this.getShopList();
  },

  //获取商品分类
  getCommodityCate() {
    let that = this;
    wx.request({
      url: url + 'app/listCommodityGroup',
      data: {
        storeId: home.getKey('storeId')
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          //判断有没有商品分类
          if (res.data.result.length>0) {
            let json = {
              id: 1,
              title: '商品',
              parent: 0
            };
            let CommodityGroup = [];
            for (let i = 0; i < res.data.result.length; i++) {
              res.data.result[i].parent = 1;
              CommodityGroup.push(res.data.result[i]);
            }
            CommodityGroup.unshift(json);
            let cate_id1 = that.data.cate_id1;
            if (that.data.cate_id1 == '') {
              cate_id1 = CommodityGroup[1].id;
            }
            that.setData({
              cate: CommodityGroup,
              cate_id1: cate_id1
            });
            that.getProjectCate();
            if (that.data.type == 1) {
              that.getShopList();
            }
          }else{
            that.setData({
              type: 2
            });
            that.getProjectCate();
          }
        } else {
          home.wxMessage(res.data.message, 'none');
        }
      }
    })
  },

  //获取项目分类
  getProjectCate() {
    let that = this;
    wx.request({
      url: url + 'app/listProjectGroup',
      data: {
        storeId: home.getKey('storeId')
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          let json = {
            id: 2,
            title: '次卡',
            parent: 0
          };
          let cate = that.data.cate;
          let len = that.data.cate.length;
          cate.splice(len, 0, json);
          for (let i = 0; i < res.data.result.length; i++) {
            res.data.result[i].parent = 2;
            len++;
            cate.splice(len, 0, res.data.result[i]);
          }
          let cate_id2 = that.data.cate_id2;
          if (that.data.cate_id1 == '') {
            cate_id2 = res.data.result[0].id;
          }
          that.setData({
            cate: cate,
            cate_id2:cate_id2
          });
          if (that.data.type == 2) {
            that.getShopList();
          }
        } else {
          home.wxMessage(res.data.message, 'none');
        }
      }
    })
  },

  //获取列表
  getShopList() {
    let requestUrl = '';
    let groupId = '';
    if (this.data.type == 1) {
      requestUrl = url + 'app/listCommodity'
      groupId = this.data.cate_id1;
    } else {
      requestUrl = url + 'app/listProject';
      groupId = this.data.cate_id2;
    }
    let that = this;
    wx.request({
      url: requestUrl,
      data: {
        storeId: home.getKey('storeId'),
        pageNo: that.data.page,
        groupId: groupId,
        memberId: home.getKey('userId'),
        keyword: that.data.value
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          let listData = that.data.listData;
          if (that.data.page == 1) {
            for (let i = 0; i < res.data.result.length; i++) {
              let pics = '';
              if (that.data.type == 1) {
                if (res.data.result[i].productPic) {
                  pics = res.data.result[i].productPic.split(',');
                  if (pics != '') {
                    res.data.result[i].pic = 'https://kyz.fbhkj.com//' + pics[0];
                  }
                }
              } else {
                if (res.data.result[i].projectPic) {
                  pics = res.data.result[i].projectPic.split(',');
                  if (pics != '') {
                    res.data.result[i].pic = 'https://kyz.fbhkj.com//' + pics[0];
                  }
                }
              }
            }
            listData = res.data.result;
          } else {
            for (let i = 0; i < res.data.result.length; i++) {
              let pics = '';
              if (that.data.type == 1) {
                if (res.data.result[i].productPic) {
                  pics = res.data.result[i].productPic.split(',');
                  if (pics != '') {
                    res.data.result[i].pic = 'https://kyz.fbhkj.com//' + pics[0];
                  }
                }
              } else {
                if (res.data.result[i].projectPic) {
                  pics = res.data.result[i].projectPic.split(',');
                  if (pics != '') {
                    res.data.result[i].pic = 'https://kyz.fbhkj.com//' + pics[0];
                  }
                }
              }
              listData.push(res.data.result[i]);
            }
          }
          that.setData({
            listData: listData
          });
        } else {
          home.wxMessage(res.data.message, 'none');
        }
      }
    })
  },

  //搜索
  onSearch(e){
    this.setData({
      value:e.detail
    })
    this.getShopList();
  },

  onClear(e){
    this.setData({
      value:''
    })
    this.getShopList();
  },

  //加入购物车
  addCar(e) {
    let that = this;
    let requestUrl = '';
    let json = {};
    let createTime = home.js_date_time(new Date() / 1000);
    json.memberId = that.data.userId;
    json.storeId = home.getKey('storeId');
    json.createBy = 'system';
    json.createTime = createTime;
    json.updateBy = '';
    json.updateTime = '';
    json.sysOrgCode = '';
    json.qty = 1;
    if (e.currentTarget.dataset.inventory == 0) {
      home.wxMessage('库存不足', 'error');
      return false;
    }
    let listData = this.data.listData;
    if (this.data.type == 1) {
      requestUrl = url + 'shopcommoditycart/ShopCommodityCart/add';
      let goodsInfo = {};
      for (let i = 0; i < listData.length; i++) {
        if (listData[i].id == e.currentTarget.dataset.id) {
          listData[i].cartNum++;
          goodsInfo = listData[i];
        }
      }
      if (goodsInfo.cartNum > goodsInfo.inventory) {
        home.wxMessage('库存不足', 'none');
        return false;
      }
      json.commodityId = e.currentTarget.dataset.id;
      json.commodityName = goodsInfo.tradeName;
      json.commoditySpec = goodsInfo.specification;
      json.commodityPic = goodsInfo.productPic;
      json.price = goodsInfo.productPrice;
    } else {
      requestUrl = url + 'shopprojectcart/ShopProjectCart/add';
      let goodsInfo = {};
      for (let i = 0; i < listData.length; i++) {
        if (listData[i].id == e.currentTarget.dataset.id) {
          listData[i].cartNum++;
          goodsInfo = listData[i];
        }
      }
      if (goodsInfo.cartNum > goodsInfo.projectNum) {
        home.wxMessage('库存不足', 'error');
        return false;
      }
      json.projectId = e.currentTarget.dataset.id;
      json.projectName = goodsInfo.projectName;
      json.projectSpec = goodsInfo.itemDescription;
      json.projectPic = goodsInfo.projectPic;
      json.price = goodsInfo.projectPrice;
    }
    this.setData({
      listData: listData,
    })
    wx.request({
      url: requestUrl,
      data: json,
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        let msg = '';
        let icon = '';
        if (res.data.code == 200) {
          msg = '添加成功';
          icon = 'success';
        } else {
          msg = '添加失败';
          icon = 'none';
        }
        home.wxMessage(msg, icon);
      }
    })
  },

  yyClick() {
      wx.navigateTo({
          url: '../yuyue/index',
      })
  },

          //小程序授权
          login() {
            wx.showLoading({
              title: '加载中...',
            })
            this.setData({
              btnState:false,
            });
            let that = this;
            wx.getUserProfile({
              desc: '用于完善会员资料',
              success: function (ress) {
                wx.login({
                  success(res) {
                    wx.request({
                      url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/updateUserNickName?storeId=' + app.globalData.storeId + '&code=' + res.code + '&xcxOpenId=' + wx.getStorageSync('openId') + '&unionId=' + wx.getStorageSync('unionId') + '&nickName' + ress.userInfo.nickName + '&headPortrait=' + ress.userInfo.avatarUrl + '&sex=保密',
                      data: {
                        storeId: app.globalData.storeId,
                        nickName: ress.userInfo.nickName,
                        headPortrait: ress.userInfo.avatarUrl,
                        sex: '保密',
                        xcxOpenId: wx.getStorageSync('openId'),
                        unionId: wx.getStorageSync('unionId')
                      },
                      method: 'POST',
                      header: {
                        "content-type": "application/json", // 默认
                      },
                      success: function (rea) {
                        if (rea.data.code == 200) {
                          wx.hideLoading({
                            success: (res) => {
                              that.setData({
                                btnState: true,
                                states:false,
                                state:2
                              })
                            },
                          })
                          wx.setStorageSync('nickName', ress.userInfo.nickName);
                          wx.setStorageSync('avatar', ress.userInfo.avatarUrl);
                          that.setData({
                            state: 2
                          });
                          wx.setStorageSync('state', 2);
                        }
                      }
                    })
                  }
                })
              },
              fail: function (res) {
                that.setData({
                  btnState: true,
                })
                wx.showToast({
                  title: '授权失败',
                  icon: 'none',
                  duration: 1500,
                })
              }
            })
          },
          register() {
            wx.showLoading({
                title: '加载中...',
            });
            let that = this;
            wx.login({
                success(res) {
                    wx.request({
                        url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/register?storeId=' + app.globalData.storeId + '&code=' + res.code,
                        data: {
                            storeId: app.globalData.storeId,
                            code: res.code
                        },
                        method: 'POST',
                        header: {
                            "content-type": "application/json", // 默认
                        },
                        success: function (rea) {
                            if (rea.data.code == 200) {
                                let states = false;
                                if (!rea.data.result.hasPhone) {
                                    that.setData({
                                        state: 1
                                    });
                                    //home.setKey('state', 1);
                                   // wx.setStorageSync('state', 1);
                                } else if (!rea.data.result.hasNickName) {
                                    states = true;
                                    that.setData({
                                        state: 0
                                    });
                                    //home.setKey('state', 0);
                                    //wx.setStorageSync('state', 0);
                                }
                                home.setKey('subscribeTencent', rea.data.result.subscribeTencent);
                                home.setKey('hasNickName', rea.data.result.hasNickName);
                                home.setKey('hasPhone', rea.data.result.hasPhone);
                                home.setKey('userId', rea.data.result.member.id);
                                home.setKey('phone', rea.data.result.member.phone);
                                home.setKey('avatar', rea.data.result.member.avatarUrl);
                                home.setKey('status', rea.data.result.member.status);
                                home.setKey('discount', rea.data.result.member.discount);
                                home.setKey('nickName', rea.data.result.member.nickName);
                                home.setKey('openId', rea.data.result.member.xcxOpenId);
                                home.setKey('unionId', rea.data.result.member.unionId);
                                let states1 = false;
                                if (rea.data.result.hasPhone && rea.data.result.hasNickName) {
                                    states1 = !rea.data.result.subscribeTencent;
                                    that.setData({
                                        state: 2
                                    });
                                    home.setKey('state', 2);
                                    wx.setStorageSync('state', 2);
                                    that.getUserInfos();
                                }
                                that.setData({
                                    states: states,
                                    states1: states1,
                                })
                                wx.hideLoading({
                                    success: (res) => {
    
                                    },
                                })
                            } else {
                                home.wxMessage(rea.data.message, 'none');
                            }
                        }
                    })
                }
            })
        },
          getPhoneNumber(e) {
            console.log(e.detail);
            wx.showLoading({
              title: '加载中...',
            });
            this.setData({
              btnState1:false,
            })
            if (e.detail.code == undefined) {
              wx.showToast({
                title: '请授权获取手机号',
                icon: 'none',
                duration: 1500,
              })
              wx.setStorageSync('state', 1);
              this.setData({
                btnState1:true,
              })
              return false;
            }
            let that = this;
            wx.request({
              url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/getPhone?storeId=' + app.globalData.storeId + '&code=' + e.detail.code + '&xcxOpenId=' + wx.getStorageSync('openId') + '&unionId=' + wx.getStorageSync('unionId'),
              data: {
                storeId: app.globalData.storeId,
                code: e.detail.code,
                xcxOpenId:wx.getStorageSync('openId'),
                unionId:wx.getStorageSync('unionId')
              },
              method: 'POST',
              header: {
                "content-type": "application/json", // 默认
              },
              success: function (res) {
                if (res.data.code == 200) {
                  wx.hideLoading({
                    success: (res) => {
                      that.setData({
                        btnState1: true,
                      });
                    },
                  })
                  wx.setStorageSync('phone', res.data.result.phone);
                  wx.setStorageSync('userId', res.data.result.id);
                  let state = 2;
                  
                  if (!wx.getStorageSync('hasNickName')) {
                    state = 0;
                  }
                  
                  that.setData({
                    state: state
                  });
                  wx.setStorageSync('state', state);
                } else {
                  wx.showToast({
                    title: '获取失败',
                    icon: 'none',
                    duration: 1500,
                  })
                }
              }
            })
          },
          onClose1() {
            this.setData({
                states: false,
            })
        },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      value:"",
      userId:home.getKey('userId'),
      page:1,
    })
    this.getTabBar().setData({
      show3: false,
      show1: false,
      show2: true,
      show4: false,
    })
    if (home.getKey('state') == 1) {
      this.getTabBar().setData({
        state: 1
      });
    } else if (home.getKey('state') == 2) {
      this.getTabBar().setData({
        state: 2
      });
    }
    this.getCommodityCate();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // let page = this.data.page;
    // this.setData({
    //   page: ++page
    // });
    // this.getShopList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})